package com.lagou.service.impl;

import com.lagou.entity.AuthCode;
import com.lagou.feign.ServiceEmailClient;
import com.lagou.repository.AuthCodeRepository;
import com.lagou.service.ICodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
public class CodeServiceImpl implements ICodeService {

    @Autowired
    private ServiceEmailClient serviceEmailClient;

    @Autowired
    private AuthCodeRepository authCodeRepository;


    @Override
    public Boolean create(String email) {
        if(StringUtils.isEmpty(email)){
            return false;
        }

        //生成6位随机数字
        String code = generateCode();

        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);
        authCode.setCreateTime(new Date());

        //code有效期十分钟
        Calendar now = Calendar.getInstance();
        now.add(Calendar.MINUTE, 10);
        authCode.setExpireTime(now.getTime());

        //保存验证码到数据库中
        authCodeRepository.save(authCode);


        //调用邮件微服务，发送验证码到邮箱
        Boolean result = serviceEmailClient.sendEmail(email, code);
        if (result) {
            return true;
        }
        return false;
    }

    @Override
    public String validate(String email, String code) {
        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        Example example = Example.of(authCode);

        //按照创建时间取出最新的一条
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        Pageable pageable = new PageRequest(0, 1, sort);
        Page<AuthCode> authCodePage = authCodeRepository.findAll(example, pageable);
        List<AuthCode> authCodeList = authCodePage.getContent();
        if (!CollectionUtils.isEmpty(authCodeList)) {
            AuthCode authCodeLatest = authCodeList.get(0);
            if (authCodeLatest.getCode().equals(code)) {
                //判断验证码有没有超时
                if (authCodeLatest.getExpireTime().before(new Date())) {
                    return "2";
                }
                return "0";
            }
        }
        return "1";
    }

    private String generateCode() {
        Random random = new Random();
        String code = "";
        for (int i = 0; i < 6; i++) {
            code += random.nextInt(10);
        }
        return code;
    }
}
